package com.heima.gateway.filter;


import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器
 *
 * @Name : AuthFilter
 * @Author : WuQiang
 * @Date : 2022-09-30 15:20
 * @Description : 全局过滤器
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = null;
        try {
            ServerHttpRequest request = exchange.getRequest();
            response = exchange.getResponse();
            //1、判断是否为登录请求
            //获取登录请求URI
            String path = request.getURI().getPath();
            if (path.contains("/login")) {
                //登录操作 直接放行
                return chain.filter(exchange);
            }
            //2、判断是否有token
            String token = request.getHeaders().getFirst("token");
            if (StringUtils.isBlank(token)) {
                //拦截 并返回错误状态码
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //3、判断token是否有效
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int status = AppJwtUtil.verifyToken(claims);

            if (status == -1 || status == 0) {
                //3.1、在有效期内
                //3.1.1、解析token中携带参数
                Integer userId = claims.get("userId", Integer.class);
                String userName = claims.get("userName", String.class);
                // 3.1.2、添加请求头并路由到微服务中
                request.mutate().header("userId", userId.toString());
                request.mutate().header("userName", userName);
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

        //3.2、无效 返回401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        //值越小越先执行
        return 0;
    }
}
